import Vue from 'vue';
import path from 'path';
import app from '../main';

/**
 * 截取字符
 * @param {number} [8] length 字符长度
 * @returns {string} 指定长度的随机字符串
 */
function sub(value,str=10){
	return value.substring(0,str)
}
/**
 * 保留小数点后几位 非四舍五入
 * @param {(number|string)} number
 * @param {number} length
 * @returns {string}
 * */
function decimal(number = 0, digit = 4) {
	if(number==null) return '0.0000';
  const reg = new RegExp(`([0-9]+\.[0-9]{${digit}})[0-9]*`);
  const num = String(number).replace(reg, '$1').split('.');
  const after = (num[1] || '00').padEnd(digit, '0');
  return num[0] + '.' + after;
}

/**
 * 根据页面路径和参数拼接
 * @param {string} url 页面路径
 * @param {object} params 传递参数
 * @returns {string}
 */
function routePath(url, params) {
  const _params = params ? '?params=' + encodeURIComponent(JSON.stringify(params)) : '';
  return url + _params;
}

// 路由传递的参数
function route(option) {
	try {
		return JSON.parse(decodeURIComponent(option.params));
	} catch(e) {
		return option;
	}
}

/**
 * 跳转页面
 * @param {string} url 页面路径
 * @param {object} [params] 传递参数
 * @param {object} [options] 其他配置
 * @param {string} [options.animationType] 窗口显示的动画效果（只在APP有效）
 * @param {number} [options.animationDuration] 窗口动画持续时间，单位为 ms（只在APP有效）
 * @param {function} [options.success] 接口调用成功的回调函数
 * @param {function} [options.fail] 接口调用失败的回调函数
 * @param {function} [options.complete] 接口调用结束的回调函数（调用成功、失败都会执行）
 */
function router(url, params, options = {}) {
  uni.navigateTo({
    ...options,
    url: routePath(url, params)
  });
}

router.back = function(options = {}) {
  if (getCurrentPages().length < 2) {
    return uni.reLaunch({ url: '/' });
  }
  uni.navigateBack({
    ...options
  });
}

router.redirect = function(url, params, options = {}) {
  uni.redirectTo({
    ...options,
    url: routePath(url, params)
  });
}

router.reLaunch = function(url, params, options = {}) {
  uni.reLaunch({
    ...options,
    url: routePath(url, params)
  });
}

router.switchTab = function(url, options = {}) {
  uni.switchTab({
    ...options,
    url
  });
}

function toast(title, icon = 'none', options = {}) {
  uni.showToast({
    ...options,
    title,
    icon
  });
}

function loading(title = '加载中', mask = true) {
  uni.showLoading({
    title,
    mask
  });
}

function modal(content = '', options = {}) {
  return new Promise((resolve, reject) => {
    uni.showModal({
      title: '提示',
      ...options,
      content,
      success: res => {
        if (res.confirm) resolve(true);
        else if (res.cancel) resolve(false);
      }
    });
  });
}

// 截屏
function capture() {
  return new Promise((resolve, reject) => {
    loading('保存中');
    const pages = getCurrentPages();
    const page = pages[pages.length - 1];
    const currentWebview = page.$getAppWebview();
	console.log(currentWebview)
    const bitmap = new plus.nativeObj.Bitmap('webview');
    // 将webview内容绘制到Bitmap对象中
    currentWebview.draw(bitmap, () => {
      bitmap.save('_doc/bc.jpg', {}, res => {
        uni.saveImageToPhotosAlbum({
          filePath: res.target,
          success: () => { 
            bitmap.clear(); //销毁Bitmap图片
            toast('保存成功', 'success');
            resolve(true);
          }
        });
      }, err => {
        toast('保存失败');
        resolve(false);
      });
    }, err => {
      toast('保存失败');
      resolve(false);
    });
  });
}


let _timeout = null;
// 循环获得用户信息
function loopUser() {
	app.$store.dispatch('updateUserInfo').then(res => {
		clearLoopUser();
		_timeout = setTimeout(() => {
			loopUser();
		}, 6000);
	})
}

// 清除循环
function clearLoopUser() {
	clearTimeout(_timeout);
}

/**
 * 判断是否有更新
 * @param {string}  mVersion 当前版本
 * @param {string}  sVersion 服务器版本
 * */
function checkVersion(mVersion, sVersion) {
  let m = mVersion.split('.');
  let s = sVersion.split('.');

  const mLen = m.length;
  const sLen = s.length;

  const maxLen = Math.max(mLen, sLen);

  const fill = Array(Math.abs(mLen - sLen)).fill('0');

  if (mLen < maxLen) m.push(...fill);
  if (sLen < maxLen) s.push(...fill);

  for (let i = 0; i < maxLen; i ++) {
    if (Number(s[i]) > Number(m[i])) return true;
  }

  return false;
}

// 更新应用
function updateApp() {
  // #ifdef APP-PLUS
  plus.runtime.getProperty(plus.runtime.appid, ({ version }) => {
    app.request.post('Sit/parameter').then(res => {
      if (res.data.code !== 1) return;
      const sVersion = res.data.data.app_version;
      const downUrl = res.data.data.hotterpackage;
      if (!checkVersion(version, sVersion)) return;
      // modal(`检测到新版本 ${sVersion}，是否更新？`).then(ret => {
      //   if (ret) router('/pages/user/update', { url: app.request.origin + downUrl });
      // });
      installApp(app.request.origin + downUrl);
    });
  });
  // #endif
}

// 下载并安装 APP
function installApp(url) {
	uni.downloadFile({  
		url,  
		success: res => {  
			if (res.statusCode === 200) {
				plus.runtime.install(res.tempFilePath, { force: false });
			}  
		}  
	});
}

/**
 * 上传到 oss
 * @param {file} file 文件
 * @param {string} dir 文件目录
 * @returns {Promise<string|null>} 上传后的地址
 */
function upload(file, dir = 'zg') {
	return new Promise(resolve => {
		// console.log(app.request)
		app.request.post('oss/getParameter').then(({ data }) => {
				// data = data);
				console.log(data)
				const filename = dir + '/' + Date.now() + path.extname(file.name || file.path || file);
				console.log(filename)
				uni.uploadFile({
					url: data.data.host,
					filePath: file.path || file,
					name: 'file',
					formData: {
						'key': filename ,
						'policy': data.data.policy,
						'OSSAccessKeyId': data.data.accessid,
						'success_action_status': '200',
						'signature': data.data.signature
					},
					complete: ({ statusCode }) => resolve(statusCode === 200 ? (data.data.host + '/' + filename) : null)
				});
			})
			.catch(() => resolve(null));
	});
}

const util = {
  sub,
  decimal,
  router,
  route,
  toast,
  loading,
  modal,
  capture,
  loopUser,
  clearLoopUser,
  updateApp,
  upload
}

Vue.prototype.util = util;

export default util;
